<template>
	<div class="app-container">
		<div class="filter-container">
			<!-- <el-input  class="w-100" v-model="queryForm.keyword" placeholder="关键字搜索" /> -->
			<!-- <el-button type="primary" :icon="Search"  @click="handleSearch">搜索</el-button> -->
			<!-- <el-button class="green-button"  :icon="Plus"  @click="handleSearch">增加</el-button> -->
			<el-button class="green-button" :icon="Plus" @click="refreshTableInfo">刷新列表</el-button>
		</div>
		<div class="table-con">
			<el-table v-loading="loading" :data="tableData" style="width: 100%" row-key="id" border>
				<el-table-column prop="id" label="手机id" width='180' />
				<el-table-column prop="type" label="手机型号" />
				<el-table-column prop="brand" label="手机品牌" />
				<el-table-column prop="fbl" label="分辨率" />
				<el-table-column prop="ld" label="屏幕亮度" />
				<el-table-column prop="state" label="连接状态">
					<template #default="scope">
						<div style="color:green">连接中</div>
						<!-- <div v-else>未连接 </div> -->
					</template>
				</el-table-column>

				<el-table-column prop="state" label="任务状态">
					<template #default="scope">
						<div v-if="tasks && tasks[scope.row.id]" style="color:green">跑分中</div>
						<div v-else>已停止 </div>
					</template>
				</el-table-column>
				<!-- <el-table-column prop="title" label="介绍"/>
        <el-table-column prop="phone" label="联系方式"/>
        <el-table-column prop="address" label="地址"/> -->
				<!-- <el-table-column prop="createTime" label="日期"/> -->
				<el-table-column fixed="right" label="操作" width="200">
					<template #default="scope">

						<!-- <el-button link size="small" @click="takePhoto(scope.row.id, true)">截屏</el-button>
						<el-button v-if="tasks && !tasks[scope.row.id]" link type="primary" size="small"
							@click="startDevices(scope.row.id,scope.row.fbl)">执行任务</el-button>
						<el-popconfirm v-else title="确认停止任务?" @confirm="deleteBtnClick(scope.row.id)">
							<template #reference>
								<el-button size="small" type="warning" link @click="">停止任务</el-button>
							</template>
						</el-popconfirm>
						<el-button link size="small" @click="startApp(scope.row.id,scope.row.fbl)">启动app</el-button> -->

						<el-button link size="small" @click="takePhoto(scope.row.id, true)">截屏</el-button>
						<el-button v-if="tasks && !tasks[scope.row.id]" link type="primary" size="small"
							@click="startDevices(scope.row.id,scope.row.fbl)">执行任务</el-button>
						<el-popconfirm v-else title="确认停止任务?" @confirm="deleteBtnClick(scope.row.id)">
							<template #reference>
								<el-button size="small" type="warning" link @click="">停止任务</el-button>
							</template>
						</el-popconfirm>
						<el-button link size="small" @click="startApp(scope.row.id,scope.row.fbl)">启动app</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<Pagination v-model:page="pagination.pageNum" v-model:size="pagination.pageSize" :total="total"
			@pagination="getTableData" />
		<!-- <el-image style="height: 300px;width: 300px;" :src="url" /> -->
		<el-dialog v-model="dialogVisible" title="截图" width="500">
			<el-image :src="'data:image/png;base64,' + url" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="dialogVisible = false">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>

</template>
<script setup lang="ts">
	import { reactive, ref, onMounted } from 'vue'
	import { Search, Plus, Delete, Edit, Loading } from '@element-plus/icons-vue'
	import { useTable } from '@/hooks/useTable'
	import tableApi from '@/api/table'
	import adb from "../../utils/adb"
	import { sleep, getRandomInt } from "../../utils/tools"

	import adbV2 from "../../utils/adbV2"
	import command from "@/api/command";
	import { ElDialog, ElMessageBox } from 'element-plus'
	const path = require("path");
	const { ipcRenderer } = require('electron');
	const { exec, spawn } = require("child_process");
	// 获取当前执行脚本的完整目录
	const currentWorkingDirectory = process.cwd();
	const appPath = currentWorkingDirectory;
	adb.adbPath = appPath;
	// const queryForm = reactive({
	// 	keyword: ''
	// })
	let tasks = ref({})

	let pagination = ref({
		pageNum: 1,
		pageSize: 10
	})

	let url = ref("")
	let loading = ref(true);

	let dialogVisible = ref(false)
	let pcid = ref("")
	let total = ref(0)
	let tableData = ref([]);
	// 使用示例
	// sendAdbCommand("devices", (output) => {
	// 	tableData.value = output;
	// 	total.value = 2;
	// 	loading.value = false;
	// });
	refreshTableInfo()
	onMounted(() => {
		ipcRenderer.send('message-from-renderer-pcid', 'I am ok!'); // 向主进程发送消息
		ipcRenderer.on('message-to-renderer-pcid', (event, logData) => {
			pcid.value = logData;
		})
		// adbV2.closeApp('com.xs.fm')
	});
	// 发送ADB命令的函数
	function sendAdbCommand(commands, callback) {
		// E:/xiangmu/2024/electron-vue3-elementplus-router-axios-pinia-vite-ts/src/adb-tools/adb
		exec(`${appPath}/resource/adb-tools/adb ${commands}`, (error, stdout, stderr) => {
			if (error) {
				console.error(error);
				return;
			}
			if (stderr) {
				console.error(stderr);
			}
			const arr = [];
			const devices = stdout.trim().split('\n').filter(line => line.trim().length > 0);
			devices.forEach(device => {
				const [id, state] = device.split(/\s+/);
				console.log(`设备ID: ${id}, 状态: ${state}`);
				if (id != 'List') {
					arr.push({
						id: id,
						state: state
					})
				}

			})
			callback(arr);
		});
	}
	const getTableData = async () => {
		loading.value = true;
		const res = await loadDataFunc({ ...queryForm, ...pagination })
		tableData.value = res.data.list;
		total.value = res.data.total
		loading.value = false;
	}

	const startTask = async (id, fbl) => {
		if (tasks.value[id]) startDevices(id, fbl);

	}

	const startDevices = async (id, fbl) => {
		var obj = {}
		// const schedule = require('node-schedule');
		// schedule.scheduleJob(id, '*/10 * * * * *', () => {
		// 具体任务内容....
		try {
			obj[id] = true
			zhixing(id, fbl)
			tasks.value = { ...tasks.value, ...obj };

		} catch (error) {

		}
		// })
	}
	const deleteBtnClick = async (id) => {
		// const schedule = require('node-schedule');
		// schedule.cancelJob(id)

		delete (tasks.value as any)[id];
	}

	const startApp = async (id, fbl) => {
		adbV2.serial = id;
		// var s = await adbV2.openApp('com.xs.fm', 'com.dragon.read.pages.splash.SplashActivity')
		// adbV2.swipeS(fbl, 2)
		var fb = fbl.split('*')
		adbV2.doubleTap(400, 400)
		// 947, 1319
		// await adbV2.tap(400, 400)
		// await sleep(0.05);
		// await adbV2.tap(400, 400)
		// await adbV2.back();
		// console.time("answer time");
		// console.timeLog("answer time")
		// await sleep(3);
		// console.timeLog("answer time")
	}

	const sendLog = async (data) => {
		ipcRenderer.send('message-from-renderer', data); // 向主进程发送消息
	}


	//执行命令
	const zhixing = async (id, fbl) => {
		//截图
		await takePhoto(id);
		adbV2.serial = id;
		//获取activity
		await sleep(0.5)
		var act = await adbV2.getActivity();

		var activity = act.split(' ')[4].replace(/}/g, "");
		//获取标签
		var labels = await getDeviceCommand(id);
		//获取指令
		const { extdata, cmddata } = await getServ(id, labels, activity, fbl);
		sendLog(`当前任务-${JSON.stringify(cmddata)}`);
		var fb = fbl.split('*');
		var x, y, xy1 = 0
		var xy = [];
		if (cmddata.paramtype == 'label') {
			var pos1 = cmddata.pos;
			var pos2 = cmddata.offset;
			x = Math.ceil(pos1[0]) + Math.ceil(pos2[0] * fb[0])
			y = Math.ceil(pos1[1]) + Math.ceil(pos2[1] * fb[1])
			xy = [x, y, 0, 0]
		} else if (cmddata.paramtype == 'position') {
			xy1 = cmddata.offset
			xy = [Math.ceil(xy1[0] * fb[0]), Math.ceil(xy1[1] * fb[1]), Math.ceil(xy1[2] * fb[0]), Math.ceil(xy1[3] * fb[1])]
		}
		var waitTime = cmddata.timeout;
		switch (cmddata.cmd) {
			case 'click': 	//点击
				await adbV2.tap(x, y)
				await sleep(waitTime);
				break;
			case 'dianzan': 	//点赞
				// await adbV2.tap(x, y)
				// await sleep(100);
				await adbV2.tap(x, y);
				// await adbV2.doubleTap(x, y)
				await sleep(waitTime);
				break;

			case 'swipeUp': 	//上滑
				await adbV2.swipeS(fbl)
				await sleep(waitTime);
				break;

			case 'start': 	//启动app
				await adbV2.openApp(cmddata.param)
				await sleep(1);
				break;

			case 'startAPP': 	//启动app
				await adbV2.openApp1(cmddata.param)
				await sleep(1);
				break;
			case 'wait':
				await sleep(waitTime);
				break;
			case 'stopAll':			//关闭所有
				await adbV2.closeAllApp();
				await sleep(waitTime);
				break;
			case 'back':
				await adbV2.back(id);
				await sleep(waitTime);
				break;
			case 'readDetailPage':	//看文章
				for (const value of cmddata.param) {
					//等待随机时间，上滑一次
					const randomNumber = await getRandomInt(2, 6)
					await sleep(randomNumber);
					await adbV2.swipeS(fbl)
				}
				break;
			case 'readnovel':	//读小说
				await adbV2.swipeS(fbl)
				await sleep(waitTime);
				break;

			case 'brushVideo':		//刷视频
				await adbV2.swipeS(fbl)
				await sleep(waitTime);
				break;
			case 'shoppingMall':	//逛商城
				//循环次数
				for (const value of cmddata.param) {
					//等待随机时间，上滑一次
					const randomNumber = await getRandomInt(2, 6)
					await sleep(randomNumber);
					await adbV2.swipeS(fbl)
				}
				break;

			default:
				break;
		}
		//等待
		startTask(id, fbl)

	}
	const takePhoto = async (id, bool = false) => {
		return new Promise(async (resolve, reject) => {
			adb.deviceID = id;
			//截屏放在缓存区
			var photo = await adb.adbScreenshot(appPath, id)
			var bs = btoa(new
				Uint8Array(photo).reduce((res, byte) => res + String.fromCharCode(byte), ''));
			url.value = bs;
			sendLog(`设备：${id}-截屏成功`);
			if (bool) {
				dialogVisible.value = bool;
			} else {
				resolve(bs)
			}
		});


		//截屏保存本地
		// var urls = path.join(appPath, '/src/screen-image/a.jpg')
		// var s = await adbV2.screenshot(urls)
		// var blob = new Blob([s], { type: 'image/png' });
		// console.log(blob)
		// url.value = './src/screen-image/a.jpg?' + Math.floor(Math.random() * 10) + 1;
	}

	//测试用
	function adbScreenshot(path, id) {
		return new Promise((resolve, reject) => {
			const screenshotProcess = spawn(`${path}/src/adb-tools/adb`, ['-s', id, 'exec-out', 'screencap -p ']);
			let buffer = [];
			screenshotProcess.stdout.on('data', (data) => {
				// buffer += data.toString();
				// buffer = buffer.concat(data)
				buffer = [...buffer, ...data];
			});

			screenshotProcess.on('close', (code) => {
				if (code === 0) {
					resolve(buffer);
				} else {
					reject(new Error('ADB screenshot failed'));
				}
			});

			screenshotProcess.on('error', reject);
		});
	}

	//测试用
	function execScripts(scriptPath) {
		// const tag = scriptPath.split("\\").pop();
		const tag = scriptPath;
		const process = spawn("cmd");
		// 执行python程序
		process.stdin.write(`python ${tag}\n`);
		// 接收子进程标准输出
		process.stdout.on("data", function (data) {
			console.log(data.toString());
			// console.log(JSON.stringify(data));
		});
	}

	//刷新列表
	async function refreshTableInfo() {
		var s1 = await adb.getDeviceList()
		var s2 = await getPhoneInfos(s1)
		tableData.value = s2;
		total.value = s2.length;
		loading.value = false;
	}

	//获取手机信息
	async function getPhoneInfos(list) {
		var arr = []
		for (const r of list) {
			adbV2.serial = r;
			adb.deviceID = r;
			var s2 = adbV2.getDeviceType()
			var s3 = adbV2.getDeviceBrand();
			var s4 = await adb.getScreenResolution()
			var s5 = await adb.getScreenBrightness()

			arr.push({
				id: r,
				type: s2,
				brand: s3,
				fbl: `${s4.width}*${s4.height}`,
				ld: s5
			})
		}
		return arr;
	}

	//调标签
	async function getDeviceCommand(id) {
		const data = {
			'img': url.value,
			'SN': id,
			'scale': 100
		}
		return new Promise((resolve) => {
			command.send_detect(data).then((response) => {
				// const { data } = response
				resolve(response)
			}).catch((error) => {
				stopDialog(id)
				resolve(error)
			})
		})
	}
	//调指令
	async function getServ(id, labels, activity, fbl) {
		var data = {
			'REQCODE': 100,
			'SN': id,
			'PCID': pcid.value,
			'DATA': { 'labels': labels, 'resumed': activity }
		}
		var fb = fbl.split('*');

		return new Promise((resolve) => {
			command.get_serv(data).then(async (response) => {
				const { retcode, extdata } = response;
				if (retcode == 200) {
					resolve(response);
				} else if (retcode == 201) {
					await sleep(6);
					resolve(response);
				} else if (retcode == 204) {
					await postSubmit(id, extdata.URL)
					await sleep(3);
					resolve(response);
				} else {
					stopDialog(id)
				}

			}).catch((error) => {
				console.log(error)
			})
		})
	}
	// 204提交
	async function postSubmit(id, url) {
		var data = {
			'SN': id,
			'URL': url
		}

		return new Promise((resolve) => {
			command.post_submit(data).then(async (response) => {
				const { retcode } = response;
				if (retcode == 200) {
					resolve(response);
				}

			}).catch((error) => {
				console.log(error)
			})
		})
	}


	//接口报错。停止任务提示
	async function stopDialog(id) {
		ElMessageBox.confirm(`手机id为：${id}的手机任务中断，请重启任务`)
			.then(() => {
				deleteBtnClick(id)
				done()
			})
			.catch(() => {
				// catch error
			})
	}
</script>


<style scoped>
	.w-100 {
		width: 200px;
		margin-right: 5px;
	}

</style>
